<?php

namespace app\controller\api\v1\recruit;

use app\model\message\service\StoreService;
use app\model\v1\recruit\RecruitCollection as collectionModel;
use app\model\user\User;
use app\model\user\ConfigUserLog;
use app\model\user\UserBill;
use app\model\v1\recruit\RecruitFirmType;
use app\model\v1\recruit\RecruitPersonageAuthentication;
use app\model\v1\recruit\RecruitResume;
use app\model\v1\recruit\RepairSuggestion;
use app\Request;
use app\model\v1\recovery\RecoveryUserSearchHistory;
use app\model\v1\recruit\RecruitCompany;
use app\model\v1\recruit\RecruitJob;
use app\model\v1\recruit\RecruitJobCate;
use app\model\v1\recruit\RecruitJobSeeker;
use app\model\v1\recruit\RecruitJobPoints;
use app\services\product\category\StoreProductCategoryServices;
use app\services\user\UserServices;
use app\validate\api\recruit\companyValidate;
use app\validate\api\recruit\createValidate;
use app\validate\api\recruit\jobValidate;
use app\model\v1\recruit\RecruitCollection as Model;
use think\facade\Db;


/**
 * 求职招聘
 * Class RecruitCollection
 * @package app\controller\api\recruit
 */
class RecruitCollection
{
    protected $services;
    protected $model;
    protected $company_model;
    protected $job_model;
    protected $collection_model;
    protected $job_cate_model;
    protected $resume_model;
    protected $firmtype_model;
    protected $userinfo = [];



    public function __construct(StoreProductCategoryServices $services)
    {
        $this->services = $services;
        $this->model = new RecruitJobSeeker();
        $this->company_model = new RecruitCompany();
        $this->job_model = new RecruitJobPoints();
        $this->job_data_model = new RecruitJob();
        $this->job_cate_model = new RecruitJobCate();
        $this->collection_model = new Model();
        $this->resume_model = new RecruitResume();
        $this->firmtype_model = new RecruitFirmType();
    }


    /**
     * 求职招聘 - 创建求职 - 个人简历
     * @return mixed
     */
    public function create(Request $request)
    {
        $data = $request->postMore([
            ['user_name', ''],
            ['user_age', ''],
            ['job_type', ''],
            ['industry_id', ''],
            ['salary_min', ''],
            ['salary_max', ''],
            ['province_id', ''],
            ['city_id', ''],
            ['district_id', ''],
            ['province_name', ''],
            ['city_name', ''],
            ['district_name', ''],
            ['school', ''],
            ['degree', ''],
            ['profession', ''],
            ['graduation_time', ''],
            ['user_job_status', 0],
            ['advantage', ''],
            ['project_experience', ''],
            ['work_experience', ''],
            ['working_years', ''],
            ['user_avatar', '']
        ]);
        validate(createValidate::class)->check($data);

        $uid = $request->uid();
        $data['uid'] = $uid;
        $this->param_unset($data);

        $userinfo = User::where("uid", $uid)->find();
        $data['phone'] = $userinfo['phone'] ?? '';
        $res = RecruitJobSeeker::where(['uid'=>$request->uid()])->find();
        if ($res){
            return app('json')->fail('求职意向已经存在,无需添加');
        }
        RecruitJobSeeker::create($data);

        ConfigUserLog::ResisUserConfigLog($uid,'recruit');

        return app('json')->success('求职意向添加成功');
    }


    /**
     * 求职招聘 - 修改个人简历
     * @param $id
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function update(Request $request, $id)
    {
        $data = $request->postMore([
            ['user_name', ''],
            ['user_age', ''],
            ['job_type', ''],
            ['industry_id', ''],
            ['salary_min', ''],
            ['salary_max', ''],
            ['province_id', ''],
            ['city_id', ''],
            ['district_id', ''],
            ['province_name', ''],
            ['city_name', ''],
            ['district_name', ''],
            ['school', ''],
            ['degree', ''],
            ['profession', ''],
            ['graduation_time', ''],
            ['user_job_status', 0],
            ['advantage', ''],
            ['project_experience', ''],
            ['work_experience', ''],
            ['working_years', ''],
            ['user_avatar', '']
        ]);
        validate(createValidate::class)->check($data);

        $this->param_unset($data);
        $res = $this->model->where("id", $id)->update($data);
        if ($res >= 0) {
            return app('json')->success('求职意向更新成功');
        }

        ConfigUserLog::ResisUserConfigLog($request->uid(),'recruit');

        return app('json')->fail('当前id数据不存在');
    }


    public function param_unset (&$params)
    {
        unset($params['token']);
        unset($params['sign']);
        unset($params['app_id']);
        unset($params['sign_key']);
        unset($params['version']);
    }


    /**
     * 求职招聘 - 我的 - 获取个人简历
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function detail(Request $request)
    {
        $param = $request->param();
        if(empty($param["id"])) return app('json')->fail('id不能为空');
        $where['id'] = $param["id"];
        $uid = $request->uid();
        //$where['uid'] = $uid ?? 0;

        $seeker = $this->model
            ->with([
                'workingyears'=> function($query) {
                    $query->where('type',1)->field ('job_name,code');
                },
                'degrees'=> function($query) {
                    $query->where('type',2)->field ('job_name,code');
                },
                'userjobstatus'=> function($query) {
                    $query->where('type',3)->field ('job_name,code');
                },
                'Collection'=> function($query) use ($where){
                    $query->where('type',1);
                  //  $query->where('user_id', $where['uid']);
                },
                'industry'=> function($query) use ($where){
                    $query->field ('*');
                }
            ])
            ->where($where)
            ->find();
	    $seeker['is_liao']=false;

        if ($seeker||$uid) {
            $record =Db::name('store_service_record')->where ('user_id', $uid)->where ('to_uid',$seeker['uid'])->find();
            if ($record){
                $seeker['is_liao']=true;
            }
            return app('json')->success($seeker->toArray());
        }
        return app('json')->fail('个人简历不存在');
    }


    /**
     * 获取打电话次数/联系次数
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getPhoneChatCount(Request $request)
    {
        $param = $request->param();
        if(empty($param["job_id"])) return app('json')->fail('job_id不能为空');

        $uid = $request->uid();
        $where['id'] = $param["job_id"];
        $seeker = $this->job_data_model->field("*")
            ->with([
                'industry'=> function($query) {
                    $query->field('*');
                },
            ])
            ->where($where)
            ->find();
        if ($seeker) {
            $seeker = $seeker->toArray();
            $collection_find = collectionModel::where(["user_id"=>$uid, "type"=>2])->where("job_id", $param["job_id"])->find() ?? [];
            $seeker["is_collection"] = !empty($collection_find) ? 1 : 2;
            return app('json')->success($seeker);
        }
        return app('json')->fail('job_id不存在');
    }


    /**
     * 编辑打电话次数/联系次数
     * @param Request $request
     * @return \think\Response
     */
    public function setPhoneChatCount(Request $request)
    {
        $param = $request->param();
        if(empty($param["job_id"])) return app('json')->fail('job_id不能为空');
        if(empty($param["phone_type"])) return app('json')->fail('phone_type不能为空');

        try {

            $res = RecruitJob::setPhoneChatCount($param);
            return app('json')->success('编辑成功');

        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 创建企业认证
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function create_company(Request $request)
    {
        $data = $request->postMore([
            ['business_license_name', ''],
            ['company_type', ''],
            ['business_license_images', ''],
            ['corporate_capacity_images', ''],
            //['name', ''],
            ['province_id', ''],
            ['province_name', ''],
            ['city_id', ''],
            ['city_name', ''],
            ['district_id', ''],
            ['district_name', ''],
            ['address', ''],
            ['company_nums', ''],
            ['logo_image', ''],
        ]);
        validate(companyValidate::class)->check($data);

        $res = $this->company_model->where(['business_license_name' => $data['business_license_name']])->whereIn("audit_state", [0, 1])->find();
        if ($res){
            return app('json')->fail('此企业认证已经存在,无需添加');
        }

        $images_arr = explode(",", $data["corporate_capacity_images"]);
        if(empty($images_arr)) return app('json')->fail('法人身份证照片必须提供！');
        foreach ($images_arr as $key => $val){
            if($key == 0) {
                if(empty($val)) return app('json')->fail('法人身份证正面必须提供！');
            }
            if($key == 1) {
                if(empty($val)) return app('json')->fail('法人身份证反面必须提供！');
            }
        }

        $uid = $request->uid();
        $data = $request->post();
        $data['uid'] = $uid;

        $reg_find = RecruitPersonageAuthentication::where(["u_id"=>$uid])->whereNull("delete_at")->find();
        if(empty($reg_find))  return app('json')->fail('请先实名认证！');
        if(!empty($find["status"])){
            if($find["status"] == 1) {
                return app('json')->fail('审核中，请实名审核通过后再发布！');
            }else if($find["status"] == 3) {
                return app('json')->fail('审核未通过，请实名认证审核！');
            }
        }

        $data['acquiesce'] = 1;
        $this->param_unset($data);


        $count = $this->company_model->where('uid', $request->uid())->count();
        if ($count){
            $data['acquiesce'] = 2;
        }
        $this->company_model->create($data);
        return app('json')->success('企业认证添加成功');
    }


    /**
     * 编辑企业认证
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function update_company(Request $request)
    {
        $data = $request->postMore([
            ['business_license_name', ''],
            ['company_type', ''],
            ['business_license_images', ''],
            ['corporate_capacity_images', ''],
            ['name', ''],
            ['province_id', ''],
            ['province_name', ''],
            ['city_id', ''],
            ['city_name', ''],
            ['district_id', ''],
            ['district_name', ''],
            ['address', ''],
            ['company_nums', ''],
            ['logo_image', ''],
            ['id', ''],
        ]);
        validate(companyValidate::class)->check($data);
        if(empty($data["id"])) return app('json')->fail('id不能为空');

        $images_arr = explode(",", $data["corporate_capacity_images"]);
        if(empty($images_arr)) return app('json')->fail('法人身份证照片必须提供！');
        foreach ($images_arr as $key => $val){
            if($key == 0) {
                if(empty($val)) return app('json')->fail('法人身份证正面必须提供！');
            }
            if($key == 1) {
                if(empty($val)) return app('json')->fail('法人身份证反面必须提供！');
            }
        }

        $data = $request->post();
        $this->param_unset($data);
        $seeker = $this->company_model->where("id", $data["id"])->find();
        if ($seeker) {
            $res = $seeker->save($data);
            if ($res){
                $update_state['audit_state'] = 0;
                $seeker->save($update_state);
            }
	        RecruitJob::where("f_id", $data["id"])->update(["status"=>2]);
            return app('json')->success('企业更新成功');
        }
        return app('json')->fail('当前id数据不存在');
    }


    /**
     * 获取企业认证详情
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCompany(Request $request)
    {
        $param = $request->param();

        $find = $this->company_model
            ->with ('companytype')->where (function ($query)use ($param){
                if ($param['id']) $query->where('id',$param['id']);
            })->find ();
        if(!empty($find)){
            $find = $find->toArray();
            $find["job_list"] = RecruitJob::where("f_id", $find["id"])->where("status", 1)->select()->toArray();
        }

        return app('json')->success($find ?? []);
    }


    /**
     * 获取企业认证列表
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCompanyList(Request $request)
    {
        $data['data'] = $this->company_model->where('uid',$request->uid())->whereNull("delete_at")->field('*')->select();
        $data['count'] = $this->company_model->where('uid',$request->uid())->whereNull("delete_at")->count();
        return app('json')->success($data);
    }


    /**
     * 删除企业
     * @param Request $request
     * @return \think\Response
     */
    public function deleteCompany(Request $request)
    {
        $param = $request->post();
        if(empty($param['id'])) return app('json')->fail('id不能为空');

        $ids = explode(",", $param["id"]);

        $uid = $request->uid();
        //$uid_company_find = $this->company_model->where('uid',$uid)->where("id", $param["id"])->find();
        //if(empty($uid_company_find)) return app('json')->fail('没有此信息');

        $res = $this->company_model->where('uid',$uid)->whereIn("id", $ids)->update(["delete_at"=>date("Y-m-d H:i:s")]);
	    RecruitJob::whereIn("f_id", $ids)->update(["status"=>2]);

	    return app('json')->success('success');
    }


    /**
     * 切换企业
     * @param $id
     * @return \think\Response
     */
    public function update_company_acquiesce(Request $request)
    {
        $id = $request->param("id", "");
        if(empty($id)) return app('json')->fail('id不能为空');

        try {
            $seeker = $this->company_model->where("id", $id)->find();
            if ($seeker['audit_state'] == 1) {   // $seeker['acquiesce'] == 2 &&
                $res = $seeker->save(['acquiesce' => 1]);
                if ($res) {
                    $this->company_model->where('uid', $request->uid())->where ('id','<>',$id)->update([
                        'acquiesce' => 2
                    ]);
                    return app('json')->success('切换成功');
                }
                return app('json')->fail('切换失败');

            }else{
                return app('json')->fail('不能切换');
            }
        } catch (\Throwable $e) {
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 求职使用积分配置
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function jobpoints_list(Request  $request)
    {
        $type = $request->param("type", "1");
        $jobs = $this->job_model->whereNull("delete_time")->where(["status" =>1, "type" => $type])->select()->toArray();
        return app('json')->success($jobs);
    }


    /**
     * 新建岗位
     * @return mixed
     */
    public function createJob(Request $request)
    {
        $data = $request->postMore([
            ['position', ''],
            ['job_type', ''],
            ['industry_id', ''],
            ['industry_type_id', ''],
            ['province_id', ''],
            ['city_id', ''],
            ['district_id', ''],
            ['province_name', ''],
            ['city_name', ''],
            ['district_name', ''],
            ['address', ''],
            ['experience_required', ''],
            ['salary_min', ''],
            ['salary_max', ''],
            ['benefits', ''],
            ['job_requirements', ''],
            ['is_phone', ''],
            ['f_id', ''],
            ['u_name', ''],
            ['u_phone', ''],
            ['phone_count', ''],
            ['chat_count', ''],
            ['Integral_usage', ''],
        ]);
        validate(jobValidate::class)->check($data);

        $this->param_unset($data);

        $uid = $request->uid();
        $companydata = RecruitCompany::where("id", $data['f_id'])->find();
        if (!$companydata) return app('json')->fail('没有找到此企业');
        if ($companydata['audit_state'] != 1) return app('json')->fail('此企业没有审核或审核未通过');

        $userServices = app()->make(UserServices::class);
        $userinfo = $userServices->getUserInfo($uid);
        try{
            Db::startTrans();
            $data['province_id']    = $companydata['province_id'];
            $data['province_name']  = $companydata['province_name'];
            $data['city_id']        = $companydata['city_id'];
            $data['city_name']      = $companydata['city_name'];
            $data['district_id']    = $companydata['district_id'];
            $data['u_id']           = $uid;
            $data['f_id']           = $companydata['id'];
            $data['kefu_id']        = RecruitCompany::getCompanyKefuId($companydata['id'], $uid) ?? $uid;
            $data['district_name']  = $companydata['district_name'];
            $data['address']        = $companydata['address'];
            $data['chat_count_use']         = $data['chat_count'];
            $data['phone_count_use']        = $data['phone_count'];
            $data['benefits']       = $data['benefits'] ?? $request->post('benefits','');

            $count = $this->job_data_model->where ('position',$data['position'])->where ('f_id',$data['f_id'])->count ();
            if ($count > 0) return app('json')->fail('岗位名称不能重复');

            if ($userinfo['integral'] >= $data['Integral_usage']){
                $result = $this->job_data_model->create($data)->getLastInsID();
            }else{
                Db::rollback();
                return app('json')->fail('积分不足');
            }

            if ($result) {
                Db::name('user')->where('uid', $uid)->dec('integral', $data['Integral_usage'])->update();

                $add = [
                    'uid' => $uid,
                    'pm' => 0,
                    'title' => '发布岗位消耗积分',
                    'category' => 'integral',
                    'type' => 'publish_job',
                    'number' => $data['Integral_usage'],
                    'balance' => $user["integral"] ?? 0 + $data['Integral_usage'],
                    'mark' => '用户发布岗位消耗积分'.$data['Integral_usage'],
                    'add_time' => time(),
                ];
                UserBill::create($add);

                Db::name('user_point_record')->insert(['user_id' => $uid,'score'=>$data['Integral_usage'],'type'=>4,'job_id'=>$result]);

                ConfigUserLog::ResisUserConfigLog($uid, 'recruit');

                Db::commit();

                return app('json')->success('招聘信息添加成功');
            }

            Db::rollback();
            return app('json')->fail('招聘信息添加失败');
        }catch (\Throwable $e){
            Db::rollback();
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 查询/1工作经验 /2学历/ 3求职状态/4薪资
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getJobCateList()
    {
        $seekers = $this->job_cate_model->field('job_name,code,type,id')->cache('true')->select()->toArray();
        $result = array ();
        foreach($seekers as $k=>$v){
            $result[$v['type']][] = $v;  //根据type 进行数组重新赋值
        }
        return app('json')->success($result);
    }


    /**
     * 获取求职列表
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DbException
     */
    public function jobseeker_list(Request $request)
    {
        $param = $request->param();
        $param['page'] =  $param['page'] ?? 1;
        $param['limit'] = $param['limit'] ?? 10;

        $uid = $request->uid();
        $industry_ids = RecruitJob::getUidJobIndustryIds($uid);
        if(empty($industry_ids)) return app('json')->success([]);

        $seekers['data'] = $this->model
            ->field ('id,uid,user_name,industry_id,salary_min,salary_max,working_years,advantage,user_job_status,degree,city_name,district_name,user_avatar')
            ->with(['workingyears'=> function($query) {
                $query->where('type',1)->field('job_name,code');
            }])
            ->with(['degrees'=> function($query) {
                $query->where('type',2)->field('job_name,code');
            }])
            ->with(['userjobstatus'=> function($query) {
                $query->where('type',3)->field('job_name,code');
            }])
            ->with('industry')
            ->where(function ($query)use ($param, $industry_ids){
                $query->where(['status'=>1]);
                $query->whereIn('industry_id', $industry_ids);
                if (!empty($param['province_id']))      $query->where(['province_id'=>$param['province_id']]); //省
                if (!empty($param['city_id']))          $query->where(['city_id'=>$param['city_id']]); //市
                if (!empty($param['district_id']))      $query->where(['district_id'=>$param['district_id']]); //区
                if (!empty($param['degree']))           $query->where(['degree'=>$param['degree']]);  //学位学历
                if (!empty($param['job_type']))         $query->where(['job_type'=>$param['job_type']]);  //职位类型（如全职、兼职等）
                if (!empty($param['industry_id']))      $query->where(['industry_id'=>$param['industry_id']]);  //行业
                if (!empty($param['working_years']))    $query->where(['working_years'=>$param['working_years']]);  //工作年限
                if (!empty($param['user_job_status']))  $query->where(['user_job_status'=>$param['user_job_status']]);  //求职状态
                if (!empty($param['salary'])){   //薪资筛选
                    $salary = explode(",", $param['salary']);
                    $query->where('salary_min','>=',$salary[0]);
                    $query->where('salary_max','<=',$salary[1]);
                }
            })
            ->page($param['page'],$param['limit'])
            ->select();

        $seekers['count'] = $this->model
            ->where(function ($query)use ($param, $industry_ids){
                $query->where(['status'=>1]);
                $query->whereIn('industry_id', $industry_ids);
                if (!empty($param['province_id']))      $query->where(['province_id'=>$param['province_id']]); //省
                if (!empty($param['city_id']))          $query->where(['city_id'=>$param['city_id']]); //市
                if (!empty($param['district_id']))      $query->where(['district_id'=>$param['district_id']]); //区
                if (!empty($param['degree']))           $query->where(['degree'=>$param['degree']]); //学位学历
                if (!empty($param['job_type']))         $query->where(['job_type'=>$param['job_type']]); //职位类型（如全职、兼职等）
                if (!empty($param['industry_id']))      $query->where(['industry_id'=>$param['industry_id']]); //行业
                if (!empty($param['working_years']))    $query->where(['working_years'=>$param['working_years']]); //工作年限
                if (!empty($param['user_job_status']))  $query->where(['user_job_status'=>$param['user_job_status']]); //求职状态
                if (!empty($param['salary'])){  //薪资筛选
                    $salary = explode(",", $param['salary']);
                    $query->where('salary_min','>=',$salary[0]);
                    $query->where('salary_max','<=',$salary[1]);
                }
            })
            ->count();

        return app('json')->success($seekers);
    }


    /**
     * 招聘列表
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function job_list(Request $request)
    {
        $param = $request->param();
        $param["page"] = $param["page"] ?? 1;
        $param["limit"] = $param["limit"] ?? 10;

        if (!empty($param['position']) && $request->uid()) {
            if (!RecoveryUserSearchHistory::where(['uid' => $request->uid(), 'keyword' => $param['position'],'topic' => '2'])->count()) {
                RecoveryUserSearchHistory::create([
                    'uid' => $request->uid(),
                    'topic' => 2,
                    'keyword' => $param['position'],
                ]);
            }
        }
        if (empty($param['industry_type_id'])) return app('json')->fail('行业类型不能为空');


        $where = [];
        $where['industry_type_id'] = $param['industry_type_id'];
        $where['status'] = 1;
        if (!empty($param['industry_id'])) $where['industry_id'] = $param['industry_id'];
        if (!empty($param['job_type'])) $where['job_type']= $param['job_type'];
        if (!empty($param['position'])) $where['position'] = ['like', '%' . $param['position'] . '%'];
        if (!empty($param['user_id'])) $where['user_id'] = $param['user_id'];


        $order =[];
        if (!empty($param['ctime_status'])){
            $order['updated_at']='desc';
        }
        if (!empty($param['page_view'])){
            $order['page_view']=$param['page_view'];
        }
        if(empty($order)) $order =["id" => "desc"];

        // 审核通过的数据
        $jobs['data'] = RecruitJob::where($where)->with([
            'industry' => function ($q) {
                $q->field(['id', 'industry_name']);
            }
        ])->with([
            'company' => function ($q) {
                $q->field(['id', 'business_license_name', 'name']);
            }
        ])->where (function ($query) {
        })->order ($order)->page ($param['page'],$param['limit'])->field ('id,u_id,f_id,position,industry_id,salary_min,salary_max,city_name,district_name,benefits')->select()->each(function (&$item) {
            $item['salary_range'] = $item['salary_min'] . 'K-' . $item['salary_max'] . 'K';
        })->toArray();

        $jobs['count'] = RecruitJob::where($where)->page ($param['page'],$param['limit'])->count();

        return app('json')->success($jobs);
    }


    /**
     * 获取招聘详情
     * @return mixed
     */
    public function getjob(Request $request)
    {
        $id = $request->param('id');
        if(empty($id)) return app('json')->fail('id不能为空');
	    $uid =  $request->uid();
        $where = ['id' => $id];
        $job = RecruitJob::where($where)
            ->with([
            'industry' => function ($q) {
                $q->field(['id', 'industry_name']);
            },
            'company' => function ($q) {
                $q->field(['id', 'business_license_name', 'name','company_nums,logo_image']);
            },'Collection' => function ($q)use ($uid) {
                $q->where('type',2)->where('user_id',$uid)->find();
            }

        ])->find();
	    $liao  = $job['kefu_id']==null ?$job['u_id']:$job['kefu_id'];
	    if ($job) {
            $job = $job->toArray();
            $job['kefu_id'] = RecruitCompany::getCompanyKefuId($job['f_id'], $job['u_id']);
					$record =Db::name('store_service_record')->where ('user_id', $uid)->where ('to_uid',$liao)->find();
				$job['is_liao']=false;
					if ($record){
						$job['is_liao']=true;
					}

            return app('json')->success($job);
        }
        return app('json')->fail('招聘信息不存在');
    }


    /**
     * 添加收藏
     * @param Request $request
     * @return \think\Response
     */
    public function createCollection(Request $request)
    {
        $param = $request->post();
        if(empty($param["job_id"]))  return app('json')->fail('job_id字段不能为空');
        if(empty($param["type"]))  return app('json')->fail('type字段不能为空');

        $uid = $request->uid();
        $add = [
            "job_id"    => $param["job_id"],  //收藏人才或者收藏职位
            "type"      => $param["type"],  //1人才  2职位
            "ctime"     => date("Y-m-d H:i:s"),  //添加时间
            "user_id"   => $uid,  //用户id
            "position_id"    => $param["position_id"] ?? '',  //岗位id
        ];
        //Model::create($add);
        $id = app()->make(Model::class)->insertGetId($add);

        return app('json')->success('success',["id"=>$id]);
    }


    public function getAllArea()
    {
        $data = $this->getAreaTree();
        return app('json')->success($data);
    }

    public function getAreaTree($id=0)
    {
        $result = [];
        $data = Db::name('area')->where('parent_id',$id)->select();
        if ($data){
            foreach($data as $k=> $v) {
                $result[$k] = $v;
                $list = $this->getAreaTree($v['id']);
                if ($list){
                    foreach($list as $val) {
                        $result[$k]['child'][] = $val;
                    }
                }
            }
        }
        return $result;
    }


    /**
     * 我收藏的 - 求职者列表
     * @param Request $request
     * @return \think\Response
     */
    public function getCollectionList(Request $request)
    {
        $param = $request->param();
        $param['page'] =  $param['page'] ?? 1;
        $param['limit'] = $param['limit'] ?? 10;

        $data['data'] = Model::field ('id,job_id,ctime,user_id,type')
            ->with(['recruitjobseeker'=> function($query) {
                $query->field('*');
            }])
            ->page($param['page'],$param['limit'])
            ->select()->toArray();

        $data['count'] = Model::field ('id,job_id,ctime,user_id,type')
            ->with(['recruitjobseeker'=> function($query) {
                $query->field('*');
            }])
            ->count();

        return app('json')->success($data);
    }


    /**
     * 切换身份
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DbException
     */
    public function update_acquiesce(Request $request)
    {
        $param = $request->post();
        $job_standing = $param['job_standing'];
        Db::name ('user')->where ('uid',$request->uid())->update(['job_standing'=>$job_standing]);
        return app('json')->success('切换成功');
    }


    /**
     * 个人简历上下架
     * @param $id
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function up_seeker_status(Request $request)
    {
        $id = $request->post('id',0);

        $seeker = $this->model->find($id);
        if ($seeker) {
            if ($seeker['status']==1){
                $status = 2;
                $msg = '下架成功';
            }else{
                $status = 1;
                $msg = '上架成功';
            }
            $this->model->where ('id',$id)->update(['status'=>$status]);
            return app('json')->success('求职意向'.$msg);
        }
        return app('json')->success('求职者意向不存在');
    }


    /**
     * 求职招聘 - 我的 - 获取个人简历
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getSeekerPersonDetail(Request $request)
    {
        $param = $request->param();
        //if(empty($param["id"])) return app('json')->fail('id不能为空');
        $where['uid'] = $request->uid();
        $seeker = $this->model
            ->with(['workingyears'=> function($query) {
                $query->where('type',1)->field ('job_name,code');
            }])
            ->with(['degrees'=> function($query) {
                $query->where('type',2)->field ('job_name,code');
            }])
            ->with(['userjobstatus'=> function($query) {
                $query->where('type',3)->field ('job_name,code');
            }])
            ->with(['Collection'=> function($query, $where) {
                $query->where('type',1);
                $query->where('user_id', $where['uid']);
            }])
            ->with('industry')
            ->where($where)
            ->find();
        if ($seeker) {
            return app('json')->success($seeker->toArray());
        }
        return app('json')->fail('个人简历不存在');
    }


    /**
     * 在线简历上下架
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function up_job_status(Request $request)
    {
        $id = $request->post('id',0);

        $seeker = $this->job_data_model->where('id',$id)->find();
        if ($seeker) {
            if ($seeker['status']==1){
                $status = 2;
                $msg = '下架成功';
            }else{
                $status = 1;
                $msg = '上架成功';
            }
            $this->job_data_model->where ('id',$id)->update(['status'=>$status]);
            return app('json')->success('岗位'.$msg);
        }
        return app('json')->fail('岗位不存在');
    }


    /**
     * 取消收藏
     * @param Request $request
     * @return \think\Response
     */
    public function del_Collection(Request $request)
    {
        $id = $request->post('id',0);
        $id = explode(",", $id);
        $res = $this->collection_model->where('id','in',$id)->delete();

        if ($res >= 0) {
            return app('json')->success('取消收藏成功');
        }
        return app('json')->fail('取消收藏失败');
    }


    /**
     * 收藏列表岗位
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DbException
     */
    public function Collection_type2(Request $request)
    {
        $data = $request->post();
        if(empty($data["page"])) return app('json')->fail('page不能为空');
        if(empty($data["limit"])) return app('json')->fail('limit不能为空');

        $uid = $request->uid();

        $res['data'] = RecruitJob::with([
                'industry' => function ($q) {
                    $q->field(['id', 'industry_name']);
                }
            ])->with([
                'company' => function ($q) {
                    $q->field(['id', 'business_license_name', 'name']);
                }
            ])->alias ('o')
            ->Join('recruit_collection re', 're.job_id = o.id')
            ->where(function ($query)use ($data, $uid){
                $query->where('re.type',2);
                $query->where('re.user_id', $uid);
	            $query->where('status',1);

            })
            ->order ('re.ctime','desc')
            ->page ($data['page'],$data['limit'])
            ->field ('o.id,re.id as collection_id ,u_id,f_id,position,industry_id,salary_min,salary_max,city_name,district_name,benefits')
            ->select()
            ->each(function (&$item) {
                $item['salary_range'] = $item['salary_min'] . 'K-' . $item['salary_max'] . 'K';
            })->toArray();

        $res['count'] = $this->collection_model
            ->where ('user_id', $uid)
            ->where('type',2)
            ->count();

        return app('json')->success($res);
    }


    /**
     * 附件简历列表
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function resumelist(Request $request)
    {
        $uid = $request->uid();
        $data = $this->resume_model->where("uid", $uid)->where('del_time',null)->select()->toArray();
        return app('json')->success($data);
    }



    /**
     * 创建上传简历
     * @param Request $request
     * @return \think\Response
     */
    public function createResume(Request $request)
    {
        $filePath = $request->post('file_url');
        if (empty($filePath)) return app('json')->fail('请上传简历');

        $fileName = $request->post('file_name');
        if (empty($fileName)) return app('json')->fail('请填写简历名称');

        $resume = $this->resume_model->save([
            'uid' => $request->uid(),
            'file_url' => $filePath,
            'file_name' => $fileName
        ]);
        return app('json')->success('简历上传成功');
    }


    /**
     * 删除附件简历
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function deleteResume(Request $request)
    {
        $id = $request->post('id',0);
        $resume = $this->resume_model->where(['id' => $id, 'uid' => $request->uid()])->where('del_time',null)->find();
        if (empty($resume)) {
            return app('json')->fail('简历不存在');
        }
	    $this->resume_model->where(['id' => $id, 'uid' => $request->uid()])->update(['del_time' => time()]);

        return app('json')->success('简历删除成功');
    }


    /**
     * 查询企业下的职位
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function job_Company_list(Request $request)
    {
        $f_id = $request->param('f_id',0);
        $where['f_id'] = $f_id ;
        $param = $request->param();
        if (!empty($param['status'])){
            $where['status'] = $param['status'];
        }
        // 审核通过的数据
        $jobs['data']= RecruitJob::where($where)->with([
                'industry' => function ($q) {
                    $q->field(['id', 'industry_name']);
                }
            ])->with([
                'company' => function ($q) {
                    $q->field(['id', 'business_license_name', 'name']);
                }
            ])->page ($param['page'],$param['limit'])
            ->field ('id,u_id,f_id,position,industry_id,salary_min,salary_max,city_name,district_name,benefits,status')
            ->select()
            ->each(function (&$item) {
                $item['salary_range'] = $item['salary_min'] . 'K-' . $item['salary_max'] . 'K';
            })->toArray();

        $jobs['count'] = RecruitJob::where($where)->page ($param['page'],$param['limit'])->count();

        return app('json')->success($jobs);
    }


    /**
     * 修改企业介绍
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function update_company_introduction(Request $request)
    {
        $id = $request->post('f_id',0);

        $data = $request->post();
        if (empty($data['introduction'])){
            return app('json')->fail('企业介绍不能为空');
        }
        $seeker = $this->company_model->find($id);
        if ($seeker) {
            $seeker->save($data);
            return app('json')->success('企业更新成功');
        }
        return app('json')->fail('企业不存在');
    }


    /**
     * 获取企业类型列表
     * @param $pid
     * @return \think\Response
     */
    public function getRecruitFirmType($pid = false)
    {
        $data = $this->getFirmTree();
        return app('json')->success($data);
    }


    public function getFirmTree($pid=0)
    {
        $result = [];
        $list = $this->firmtype_model->where('pid',$pid)->select()->toArray();

        if ($list){
            foreach($list as $k=> $v) {
                $result[$k] = $v;
                $data = $this->getFirmTree($v['id']);
                if ($data){
                    foreach($data as $vs) {
                        $result[$k]['data'][] = $vs;
                    }
                }
            }
        }
        return $result;
    }


    /**
     * 收藏列表岗位1
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DbException
     */
    public function Collection_type1(Request $request)
    {
        $data = $request->param();
        if(empty($data['page'])) return app('json')->fail('page不能为空');
        if(empty($data['limit'])) return app('json')->fail('limit不能为空');

        $uid = $request->uid();
        $seker= new RecruitJobSeeker();
        $res['data'] = $seker
            ->alias ('o')
            ->with([
                'workingyears'=> function($query) {
                    $query->where('type',1)->field ('job_name,code');
                },
                'degrees'=> function($query) {
                    $query->where('type',2)->field ('job_name,code');
                },
                'userjobstatus'=> function($query) {
                    $query->where('type',3)->field ('job_name,code');
                },
                'industry'=> function($query) use ($uid){
                    $query->field ('*');
                }
            ])
            ->Join('recruit_collection re', 're.job_id = o.id')
            ->where(function ($query)use ($data,$uid){
                $query->where('re.type',1);
                $query->where('re.user_id',$uid);
            })
            ->page ($data['page'],$data['limit'])
            ->field ('o.id,re.id as collection_id,re.job_id,re.type,re.position_id,uid,user_name,salary_min,salary_max,working_years,advantage,user_job_status,degree,city_name,district_name,user_avatar')
            ->order ('re.ctime','desc')
            ->select()->toArray();

        $res['count']= $this->collection_model
            ->where ('user_id',$uid)
            ->where('type',1)
            ->count();

        return app('json')->success($res);
    }


    /**
     * top区域搜索
     * @param Request $request
     * @return \think\Response
     */
    public function getRecruitSearchList(Request $request)
    {
        $param = $request->param();
        $param["page"] = $param["page"] ?? 1;
        $param["limit"] = $param["limit"] ?? 10;
        if(empty($param["search_type"])) return app('json')->fail('search_type不能为空');

        if (!empty($param['keyword']) && $request->uid()) {
            if (!RecoveryUserSearchHistory::where(['uid' => $request->uid(), 'keyword' => $param['keyword'],'topic' => '2'])->count()) {
                RecoveryUserSearchHistory::create([
                    'uid' => $request->uid(),
                    'topic' => 2,
                    'keyword' => $param['keyword'],
                ]);
            }
        }

        $param["user_id"] = $request->uid();
        $data = RecruitJob::getRecruitSearchList($param);

        return app('json')->success($data);
    }


    /**
     * 用户建议
     * @param Request $request
     * @return mixed
     */
    public function createSuggestion(Request $request)
    {
        $param = $request->param();
        if(empty($param["suggestion"])) return app('json')->fail('建议不能为空');
        if(empty($param["number"])) return app('json')->fail('工号不能为空');

        $param["user_id"] = $request->uid();
        $data = RepairSuggestion::createSuggestion($param);

        return app('json')->success('success');
    }

}